package thread.unsafeExample;

/**
 *
 * Created by E440 on 2017/4/19.
 */
public class SafeAccount {
    private int id;
    private double amount;

    //存钱
    public synchronized   void save(double money){
        amount+=money;
        System.out.println("In "+Thread.currentThread().getName()+ " :  After save  :"+money+", the left amount: "+amount);
    }

    //取钱方法
    public synchronized boolean draw(double number){
        if(amount>=number){

            try {
                Thread.sleep(100);//为了提高出现线程安全问题的概率
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            amount=amount-number;
            System.out.println("In "+Thread.currentThread().getName()+ " : After draw :" + number + ", the left amount: " + amount);
            return true;
        }
        return false;
    }

    public SafeAccount(int id, double amount) {
        this.id = id;
        this.amount = amount;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "UnsafeAccount{" +
                "id=" + id +
                ", amount=" + amount +
                '}';
    }
}
